package com.juku2024.juku.messaging

import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.text.TextUtils
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import coil.ImageLoader
import coil.executeBlocking
import coil.request.ImageRequest
import com.juku2024.juku.OpenActivity
import com.juku2024.juku.VideoDetailActivity
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.Constants
import com.juku2024.juku.tools.RxUtils

object NotificationUtils {

    /**
     * 自己写的加载网络图片的方法
     * img_url 图片的网址
     */
    private fun initNetWorkImage(
        context: Context,
        tag: String?,
        loadFinishListener: OnBitmapLoadFinishListener?
    ) {
        if (TextUtils.isEmpty(tag)) {
            loadFinishListener?.onBitmapLoadFinish(null)
            return
        }
        RxUtils.doObservable({
            val request = ImageRequest.Builder(context)
                .data(tag)
                .size(360, 480)
                .build()
            val imageLoader = ImageLoader.Builder(context)
                .build()
            val imageResult = imageLoader.executeBlocking(request)
            val bitmap = (imageResult.drawable as BitmapDrawable?)?.bitmap
            if (bitmap == null) {
                it.onError(NullPointerException())
            } else {
                it.onNext(bitmap)
            }
        }, {
            loadFinishListener?.onBitmapLoadFinish(it)
        }, {
            it?.printStackTrace()
        })
    }

    internal interface OnBitmapLoadFinishListener {
        fun onBitmapLoadFinish(bitmap: Bitmap?)
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private fun createNotificationChannel(channelName: String?): NotificationChannel {
        val channel = NotificationChannel(channelName, "通知", NotificationManager.IMPORTANCE_DEFAULT)
        //是否绕过请勿打扰模式
        channel.canBypassDnd()
        //闪光灯
        channel.enableLights(true)
        //锁屏显示通知
        channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
        //闪关灯的灯光颜色
        channel.lightColor = Color.RED
        //桌面launcher的消息角标
        channel.canShowBadge()
        //是否允许震动
        channel.enableVibration(true)
        //设置可绕过  请勿打扰模式
        channel.setBypassDnd(true)
        //是否会有灯光
        channel.shouldShowLights()
        //        channel.setSound(null,null);
        //设置震动模式
//        channel.setVibrationPattern(null);
        return channel
    }

    @Suppress("DEPRECATION")
    fun showBigPictureNotification(
        context: Context,
        pendingIntent: PendingIntent?,
        channel: String?,
        title: String?,
        msg: String?,
        imageUrl: String?
    ) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            return
        }
        val targetChannel = if (channel == null || TextUtils.isEmpty(channel)) {
            AppUtils.getChannelValue()
        } else {
            channel
        }
        val mNotificationManager = NotificationManagerCompat.from(context)
        //判断是否是8.0Android.O
        val mBuilder: NotificationCompat.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mNotificationManager.createNotificationChannel(createNotificationChannel(targetChannel))
            NotificationCompat.Builder(context, targetChannel)
        } else {
            NotificationCompat.Builder(context)
        }
        val smallIcon = com.blankj.utilcode.util.AppUtils.getAppIconId()
        mBuilder.setContentTitle(title) //设置通知栏标题
            .setContentText(msg) //设置通知栏内容
            .setPriority(NotificationCompat.PRIORITY_DEFAULT) //设置通知优先级
            .setContentIntent(pendingIntent) //设置通知栏点击意图
            .setAutoCancel(true)
            .setTicker(title) //通知首次出现在通知栏，带上升动画效果的
//            .setWhen(System.currentTimeMillis()) //通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
//            .setDefaults(Notification.DEFAULT_ALL) //向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
            .setSmallIcon(smallIcon) //设置通知小ICON

        if (TextUtils.isEmpty(imageUrl)) {
            //发送通知
            val notify = mBuilder.build()
//            notify.flags = notify.flags or Notification.FLAG_AUTO_CANCEL
            mNotificationManager.notify(1, notify)
            return
        }

        initNetWorkImage(context, imageUrl, object : OnBitmapLoadFinishListener {
            override fun onBitmapLoadFinish(bitmap: Bitmap?) {
                val bigPictureStyle = NotificationCompat.BigPictureStyle() // 展示图片后，可以显示新的文本
                    .setBigContentTitle(title)
                    .setSummaryText(msg)
                bigPictureStyle.bigPicture(bitmap)
                mBuilder.setStyle(bigPictureStyle)
                //发送通知
                val notify = mBuilder.build()
//                notify.flags = notify.flags or Notification.FLAG_AUTO_CANCEL
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                    return
                }
                mNotificationManager.notify(1, notify)
            }
        })
    }


    private fun getNotificationPending(context: Context?, cls: Class<*>?, videoId: Long): PendingIntent {
        val notificationIntent = Intent(context, cls)
        notificationIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
        notificationIntent.putExtra(Constants.AROUTER_KEY_VIDEO_ID, videoId)
        return PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE)
    }
    private fun getNotificationPending(clsName: String): PendingIntent {
        val notificationIntent = Intent()
        notificationIntent.setClassName(BaseApplication.context.packageName, clsName)
        notificationIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        return PendingIntent.getActivity(BaseApplication.context, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE)
    }

    fun showVideoNotification(context: Context, videoId: Long, title: String?, body: String?, image: String?, channelId: String?) {
        val pendingIntent = getNotificationPending(
            context,
            VideoDetailActivity::class.java,
            videoId
        )
        showBigPictureNotification(
            context,
            pendingIntent,
            channelId,
            title,
            body,
            image
        )
    }

    fun showMainNotification(context: Context, title: String?, body: String?, image: String?, channelId: String?){
        val pendingIntent = getNotificationPending(OpenActivity::class.java.name)
        showBigPictureNotification(
            context,
            pendingIntent,
            channelId,
            title,
            body,
            image
        )
    }

}